import requests
import ssl
from bs4 import BeautifulSoup

def ups_109():
    #------------------------109机房数据获取------------------
    url = 'https://x.x.x.x/goform/login'
    # 初始化变量，以避免 UnboundLocalError
    ups1_dianchi = '未知状态'
    ups2_dianchi = '未知状态'
    td1_content = '未知数据'
    td2_content = '未知数据'
    # 定义要发送的参数
    params = {
        'usrname': 'xxxxxxxxx',
        'pwd': 'xxxxxxxxxxxxxxxxxxxx',
        'vercodeinput': '',
        'pwdinput': '',
        'langlist': '1'
    }

    headers = {
        'If-Modified-Since': '0',
        'Content-type': 'application/x-www-form-urlencoded',
        'X-Requested-With': 'XMLHttpRequest',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0'
    }
    # -----Cookie_date这个就是获取的请求的cokie->::webs.session::3416ac19223ceeeadcce35e847ca757a----------------------
    Cookie_date = ''

    def callback(response):
        nonlocal Cookie_date
        # 处理响应的代码
        # Get the cookies from the response
        cookies = response.cookies
        # Print or use the cookies as needed
        # 获取特定cookie的值
        for cookie in cookies:
            if cookie.name == '-webserver-session-0':
                Cookie_date = cookie.value
                print(Cookie_date)
                break

    # 将参数编码为 x-www-form-urlencoded 格式
    encoded_params = "&".join([f"{key}={value}" for key, value in params.items()])

    # 忽略 SSL 验证
    requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)

    # 创建一个自定义的 SSL 上下文，并设置 TLS 版本
    custom_ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
    custom_ssl_context.set_ciphers('HIGH:!DH:!aNULL')

    # 尝试更换参数设置TLS版本
    response = requests.post(url, headers=headers, data=encoded_params, verify=False,
                             cert=None, timeout=None, allow_redirects=True,
                             stream=None, proxies=None, hooks=None, json=None)

    # 如果上面的尝试不起作用，可以尝试直接使用默认的全局上下文
    if response.status_code == 0:
        import urllib3
        urllib3.util.ssl_.DEFAULT_CIPHERS += 'HIGH:!DH:!aNULL'
        response = requests.post(url, headers=headers, data=encoded_params, verify=False)
    callback(response)

    newCookie='-webserver-session-0='+Cookie_date+'; language=1; group=3; SMS=2; menu=menu_1; ups=1; heartbeat=44000'
    #--------------------------------UPS1的数据
    url = 'https://10.106.250.34/getActiveAlarm2.asp?JumpPage=1'

    headers = {
        'Cookie': newCookie,
        'Host': '10.106.250.34',
        'If-Modified-Since': '0',
        'Referer': 'https://10.106.250.34/alarm.asp'
    }
    response = requests.get(url, headers=headers, verify=False)
    # td1_content = ""
    if response.status_code == 200:
        # 请求成功，处理返回的数据
        data = response.text  # 解析 JSON 响应数据

        # 处理编码问题，将混乱的字符解码为正确的字符串
        decoded_text = data.encode('latin1').decode('utf-8')
        # 使用BeautifulSoup解析HTML
        soup = BeautifulSoup(decoded_text, 'html.parser')
        # 找到所有的<td>标签并提取内容
        td1_content = soup.find('td').text
        td1_content = f'<span style="color:green;">{td1_content}</span>'
        print("UPS1状态: "+td1_content)


    #-----------------------------------------UPS2的数据
    url = 'https://10.106.250.34/getChartData.asp'
    newCookie='-webserver-session-0='+Cookie_date+'; language=1; group=3; SMS=2; heartbeat=45000; menu=menu_1; ups=1'
    headers = {
        'Cookie': newCookie,
        'Host': '10.106.250.34',
        'If-Modified-Since': '0',
        'Referer': 'https://10.106.250.34/alarm.asp'
    }

    response = requests.get(url, headers=headers, verify=False)
    # ups1_dianchi = ''
    if response.status_code == 200:
        # 请求成功，处理返回的数据
        data = response.text  # 解析 JSON 响应数据
        # 处理编码问题，将混乱的字符解码为正确的字符串
        decoded_text = data.encode('latin1').decode('utf-8')
        # 使用BeautifulSoup解析HTML
        soup = BeautifulSoup(decoded_text, 'html.parser')
        # 找到所有的<td>标签并提取内容
        if "主路供电" in soup.text:
            ups1_dianchi = "主路供电"
            ups1_dianchi = f'<span style="color:green;">{ups1_dianchi}</span>'
            print(ups1_dianchi)
        else:
            ups1_dianchi = "不是主路供电"
            ups1_dianchi = f'<span style="color:red;">{ups1_dianchi}</span>'
            print(ups1_dianchi)


    newCookie='-webserver-session-0='+Cookie_date+'; language=1; group=3; SMS=2; heartbeat=45000; menu=menu_1; ups=2'
    url = 'https://10.106.250.34/getActiveAlarm2.asp?JumpPage=1'

    headers = {
        'Cookie': newCookie,
        'Host': '10.106.250.34',
        'If-Modified-Since': '0',
        'Referer': 'https://10.106.250.34/alarm.asp'
    }
    response = requests.get(url, headers=headers, verify=False)
    # td2_content = ''
    if response.status_code == 200:
        # 请求成功，处理返回的数据
        data = response.text  # 解析 JSON 响应数据

        # 处理编码问题，将混乱的字符解码为正确的字符串
        decoded_text = data.encode('latin1').decode('utf-8')
        # 使用BeautifulSoup解析HTML
        soup = BeautifulSoup(decoded_text, 'html.parser')
        # 找到所有的<td>标签并提取内容
        td2_content = soup.find('td').text
        td2_content = f'<span style="color:green;">{td2_content}</span>'
        print("UPS2状态: " + td2_content)




    url = 'https://x.x.x.x/getChartData.asp'
    newCookie='-webserver-session-0='+Cookie_date+'; language=1; group=3; SMS=2; heartbeat=45000; menu=menu_1; ups=2'
    headers = {
        'Cookie': newCookie,
        'Host': '10.106.250.34',
        'If-Modified-Since': '0',
        'Referer': 'https://10.106.250.34/alarm.asp'
    }

    response = requests.get(url, headers=headers, verify=False)
    if response.status_code == 200:
        # 请求成功，处理返回的数据
        data = response.text  # 解析 JSON 响应数据
        # 处理编码问题，将混乱的字符解码为正确的字符串
        decoded_text = data.encode('latin1').decode('utf-8')
        # 使用BeautifulSoup解析HTML
        soup = BeautifulSoup(decoded_text, 'html.parser')
        # 找到所有的<td>标签并提取内容
        if "主路供电" in soup.text:
            ups2_dianchi = "主路供电"
            ups2_dianchi = f'<span style="color:green;">{ups2_dianchi}</span>'
            print(ups2_dianchi)
        else:
            ups2_dianchi = "不是主路供电"
            ups2_dianchi = f'<span style="color:red;">{ups2_dianchi}</span>'
            print(ups2_dianchi)

    #-----------109机房数据获取结束
    return {
        # 109机房UPS数据字典
        'td1_content': td1_content,
        'ups1_dianchi': ups1_dianchi,
        'td2_content': td2_content,
        'ups2_dianchi': ups2_dianchi,
    }
ups_109()